// 响应式工具函数
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'

/**
 * 响应式断点配置
 */
export const breakpoints = {
  xs: 0,
  sm: 576,
  md: 768,
  lg: 992,
  xl: 1200,
  xxl: 1400
}

/**
 * 响应式工具类
 */
export const ResponsiveUtils = {
  /**
   * 获取当前窗口尺寸
   * @returns {object} 窗口尺寸
   */
  getWindowSize() {
    if (typeof window === 'undefined') {
      return { width: 1024, height: 768 }
    }
    
    return {
      width: window.innerWidth,
      height: window.innerHeight
    }
  },

  /**
   * 获取设备类型
   * @returns {string} 设备类型
   */
  getDeviceType() {
    const { width } = this.getWindowSize()
    
    if (width < breakpoints.md) return 'mobile'
    if (width < breakpoints.lg) return 'tablet'
    return 'desktop'
  },

  /**
   * 匹配断点
   * @param {string} breakpoint - 断点名称
   * @returns {boolean} 是否匹配
   */
  matchBreakpoint(breakpoint) {
    const { width } = this.getWindowSize()
    const breakpointValue = breakpoints[breakpoint]
    
    if (breakpoint === 'xs') {
      return width < breakpoints.sm
    }
    
    const nextBreakpoint = Object.keys(breakpoints)[Object.keys(breakpoints).indexOf(breakpoint) + 1]
    const nextValue = nextBreakpoint ? breakpoints[nextBreakpoint] : Infinity
    
    return width >= breakpointValue && width < nextValue
  },

  /**
   * 获取网格列数
   * @param {object} config - 自定义配置
   * @returns {number} 列数
   */
  getGridColumns(config = {}) {
    const deviceType = this.getDeviceType()
    
    const defaultConfig = {
      mobile: 1,
      tablet: 2,
      desktop: 3
    }
    
    const finalConfig = { ...defaultConfig, ...config }
    return finalConfig[deviceType]
  },

  /**
   * 获取容器最大宽度
   * @returns {string} 最大宽度
   */
  getContainerMaxWidth() {
    const { width } = this.getWindowSize()
    
    if (width < breakpoints.sm) return '100%'
    if (width < breakpoints.md) return '540px'
    if (width < breakpoints.lg) return '750px'
    if (width < breakpoints.xl) return '970px'
    if (width < breakpoints.xxl) return '1140px'
    return '1320px'
  },

  /**
   * 获取侧边栏宽度
   * @returns {string} 侧边栏宽度
   */
  getSidebarWidth() {
    const deviceType = this.getDeviceType()
    
    const widths = {
      mobile: '280px',
      tablet: '260px',
      desktop: '240px'
    }
    
    return widths[deviceType]
  },

  /**
   * 检测是否为触摸设备
   * @returns {boolean} 是否为触摸设备
   */
  isTouchDevice() {
    if (typeof window === 'undefined') return false
    
    return 'ontouchstart' in window || navigator.maxTouchPoints > 0
  },

  /**
   * 检测是否支持hover
   * @returns {boolean} 是否支持hover
   */
  supportsHover() {
    if (typeof window === 'undefined') return true
    
    return window.matchMedia('(hover: hover)').matches
  },

  /**
   * 获取安全区域内边距
   * @returns {object} 安全区域内边距
   */
  getSafeAreaInsets() {
    if (typeof window === 'undefined' || typeof getComputedStyle === 'undefined') {
      return { top: 0, right: 0, bottom: 0, left: 0 }
    }
    
    const style = getComputedStyle(document.documentElement)
    
    return {
      top: parseInt(style.getPropertyValue('--safe-area-inset-top') || '0'),
      right: parseInt(style.getPropertyValue('--safe-area-inset-right') || '0'),
      bottom: parseInt(style.getPropertyValue('--safe-area-inset-bottom') || '0'),
      left: parseInt(style.getPropertyValue('--safe-area-inset-left') || '0')
    }
  }
}

/**
 * 移动端适配工具
 */
export const MobileAdaptation = {
  /**
   * 设置viewport
   * @param {object} config - viewport配置
   */
  setViewport(config = {}) {
    if (typeof document === 'undefined') return
    
    const defaultConfig = {
      width: 'device-width',
      initialScale: 1.0,
      maximumScale: 1.0,
      userScalable: 'no',
      viewportFit: 'cover'
    }
    
    const finalConfig = { ...defaultConfig, ...config }
    
    let viewport = document.querySelector('meta[name="viewport"]')
    if (!viewport) {
      viewport = document.createElement('meta')
      viewport.name = 'viewport'
      document.head.appendChild(viewport)
    }
    
    const content = Object.entries(finalConfig)
      .map(([key, value]) => {
        const kebabKey = key.replace(/([A-Z])/g, '-$1').toLowerCase()
        return `${kebabKey}=${value}`
      })
      .join(', ')
    
    viewport.setAttribute('content', content)
  },

  /**
   * 禁用双击缩放
   */
  disableDoubleTapZoom() {
    if (typeof document === 'undefined') return
    
    let lastTouchEnd = 0
    
    document.addEventListener('touchstart', (event) => {
      if (event.touches.length > 1) {
        event.preventDefault()
      }
    }, { passive: false })
    
    document.addEventListener('touchend', (event) => {
      const now = Date.now()
      if (now - lastTouchEnd <= 300) {
        event.preventDefault()
      }
      lastTouchEnd = now
    }, { passive: false })
  },

  /**
   * 设置状态栏样式
   * @param {string} style - 状态栏样式
   */
  setStatusBarStyle(style = 'default') {
    if (typeof document === 'undefined') return
    
    let meta = document.querySelector('meta[name="apple-mobile-web-app-status-bar-style"]')
    if (!meta) {
      meta = document.createElement('meta')
      meta.name = 'apple-mobile-web-app-status-bar-style'
      document.head.appendChild(meta)
    }
    
    meta.content = style
  },

  /**
   * 设置主题颜色
   * @param {string} color - 主题颜色
   */
  setThemeColor(color) {
    if (typeof document === 'undefined') return
    
    let meta = document.querySelector('meta[name="theme-color"]')
    if (!meta) {
      meta = document.createElement('meta')
      meta.name = 'theme-color'
      document.head.appendChild(meta)
    }
    
    meta.content = color
  },

  /**
   * 处理安全区域
   */
  handleSafeArea() {
    if (typeof document === 'undefined') return
    
    const style = document.documentElement.style
    
    // 设置CSS变量
    style.setProperty('--safe-area-inset-top', 'env(safe-area-inset-top)')
    style.setProperty('--safe-area-inset-right', 'env(safe-area-inset-right)')
    style.setProperty('--safe-area-inset-bottom', 'env(safe-area-inset-bottom)')
    style.setProperty('--safe-area-inset-left', 'env(safe-area-inset-left)')
  },

  /**
   * 初始化移动端适配
   * @param {object} config - 配置选项
   */
  init(config = {}) {
    const {
      viewport = true,
      themeColor = '#409EFF',
      statusBarStyle = 'default',
      disableDoubleTapZoom = true,
      handleSafeArea = true
    } = config
    
    if (viewport) {
      this.setViewport(typeof viewport === 'object' ? viewport : {})
    }
    
    if (themeColor) {
      this.setThemeColor(themeColor)
    }
    
    if (statusBarStyle) {
      this.setStatusBarStyle(statusBarStyle)
    }
    
    if (disableDoubleTapZoom) {
      this.disableDoubleTapZoom()
    }
    
    if (handleSafeArea) {
      this.handleSafeArea()
    }
  }
}

/**
 * 响应式组合式函数
 * @returns {object} 响应式状态和方法
 */
export function useResponsive() {
  const windowSize = ref(ResponsiveUtils.getWindowSize())
  const deviceType = computed(() => {
    const { width } = windowSize.value
    if (width < breakpoints.md) return 'mobile'
    if (width < breakpoints.lg) return 'tablet'
    return 'desktop'
  })
  
  const isMobile = computed(() => deviceType.value === 'mobile')
  const isTablet = computed(() => deviceType.value === 'tablet')
  const isDesktop = computed(() => deviceType.value === 'desktop')
  
  const updateWindowSize = () => {
    windowSize.value = ResponsiveUtils.getWindowSize()
  }
  
  onMounted(() => {
    if (typeof window !== 'undefined') {
      window.addEventListener('resize', updateWindowSize)
    }
  })
  
  onUnmounted(() => {
    if (typeof window !== 'undefined') {
      window.removeEventListener('resize', updateWindowSize)
    }
  })
  
  return {
    windowSize,
    deviceType,
    isMobile,
    isTablet,
    isDesktop,
    breakpoints
  }
}

/**
 * 响应式网格组合式函数
 * @param {object} config - 网格配置
 * @returns {object} 网格状态
 */
export function useResponsiveGrid(config = {}) {
  const { deviceType } = useResponsive()
  
  const columns = computed(() => {
    const defaultConfig = {
      mobile: 1,
      tablet: 2,
      desktop: 3
    }
    
    const finalConfig = { ...defaultConfig, ...config }
    return finalConfig[deviceType.value]
  })
  
  const gap = computed(() => {
    const gapConfig = {
      mobile: '12px',
      tablet: '16px',
      desktop: '20px'
    }
    
    return gapConfig[deviceType.value]
  })
  
  return {
    columns,
    gap
  }
}

/**
 * 响应式字体大小组合式函数
 * @param {object} config - 字体配置
 * @returns {object} 字体状态
 */
export function useResponsiveFontSize(config = {}) {
  const { deviceType } = useResponsive()
  
  const fontSize = computed(() => {
    const defaultConfig = {
      mobile: {
        xs: '12px',
        sm: '14px',
        md: '16px',
        lg: '18px',
        xl: '20px'
      },
      tablet: {
        xs: '13px',
        sm: '15px',
        md: '17px',
        lg: '19px',
        xl: '21px'
      },
      desktop: {
        xs: '14px',
        sm: '16px',
        md: '18px',
        lg: '20px',
        xl: '22px'
      }
    }
    
    const finalConfig = { ...defaultConfig, ...config }
    return finalConfig[deviceType.value]
  })
  
  return {
    fontSize
  }
}

export default {
  ResponsiveUtils,
  MobileAdaptation,
  useResponsive,
  useResponsiveGrid,
  useResponsiveFontSize,
  breakpoints
}